package com.bawei.day0129.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class BaseFragment<VM extends BaseViewModel,VDB extends ViewDataBinding> extends Fragment {
    public VM viewModel;
    public VDB dataBinding;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
       dataBinding= DataBindingUtil.inflate(inflater,initLayout(),container,false);
        return dataBinding.getRoot();
    }
    protected abstract int initLayout();
    protected abstract void initView();
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initViewModel();
        initView();
    }

    private void initViewModel() {
        Class cls=null;
        final Type type = getClass().getGenericSuperclass();
        if(type instanceof ParameterizedType){
            cls=(Class)((ParameterizedType)type).getActualTypeArguments()[0];
        }else {
            cls=getClass();
        }
        viewModel=(VM) ViewModelProviders.of(this).get(cls);
    }
}
